package com.mms.controller.admin;

import com.mms.utils.HttpUtils;
import com.mms.utils.RequestUtils;
import com.mms.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

/**
 * Created by dan3652@sina.com on 2016-12-01 11:46.
 */
@RestController
public class AjaxRequestController {
    private static final Logger logger = LoggerFactory.getLogger(AjaxRequestController.class);

    @RequestMapping("requestPost")
    public void requestPost(HttpServletRequest request, HttpServletResponse response, String remoteUrl){
        Map<String,Object> map = RequestUtils.getQueryParams(request);
        Set<String> set = map.keySet();
        StringBuffer sb = new StringBuffer(".");

        for (String object : set) {
//            if (object.equals("remoteUrl") || object.equals("shopid"))  continue;
            sb.append("&" + object + "=" + map.get(object).toString());
        }
        logger.info("参数"+sb.toString());

        try {
            String str = HttpUtils.HttpPost(remoteUrl,sb.toString().replace(".&",""));
            logger.info(str);
            ResponseUtils.renderJson(response, str);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("requestGet")
    public void requestGet(HttpServletRequest request, HttpServletResponse response,String remoteUrl){
        Map<String,Object> map = RequestUtils.getQueryParams(request);
        Set<String> set = map.keySet();
        StringBuffer sb = new StringBuffer(".");

        for (String object : set) {
            sb.append("&" + object + "=" + map.get(object).toString());
        }
        logger.info("参数"+sb.toString());

        try {
            String str = HttpUtils.HttpGet(remoteUrl,sb.toString().replace(".&",""),"UTF-8");
            logger.info(str);
            ResponseUtils.renderJson(response, str);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
